package middleware

import (
	"fmt"
	"gitee.com/chejiangyi/bsfgo/core/base2"
	"gitee.com/chejiangyi/bsfgo/core/utils"
	"gitee.com/chejiangyi/bsfgo/gin2/utils2"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
)

type HttpPrintlnMiddleware struct {
	template []string
}

func (m *HttpPrintlnMiddleware) Enabled() bool {
	return base2.BsfConfigInstance.GetHttpPrintlnEnabled()
}
func (*HttpPrintlnMiddleware) GetOrder() float64 {
	return -93
}
func (m *HttpPrintlnMiddleware) Middleware(r *gin.Engine) {
	m.template = strings.Split(base2.BsfConfigInstance.GetHttpPrintlnTemplate(), ",")
	r.Use(func(c *gin.Context) {
		start := time.Now()
		c.Next()
		timeSpan := time.Since(start).Milliseconds()
		data := utils2.WebUtil.GetRequestInfo(c)
		data["timespan"] = fmt.Sprintf("%vms", timeSpan)
		data["status"] = c.Writer.Status()
		sb := strings.Builder{}
		for _, tmp := range m.template {
			v, ok := data[tmp]
			if ok {
				sb.WriteString(fmt.Sprintf("[%v]%v;", tmp, v))
			}
		}
		utils.LogUtil.Info(sb.String())
	})

	utils.LogUtil.Info("HttpPrintlnMiddleware已开启,支持http请求和耗时打印")
}
